<template>
	<div class="hello">
		<button @click="renderDoc">
			Render docx template
		</button>
	</div>
</template>

<script>
	import Docxtemplater from "docxtemplater";
	import PizZip from "pizzip";
	import PizZipUtils from "pizzip/utils/index.js";
	import {
		saveAs
	} from "file-saver";

	// 读取并获得模板文件的二进制内容
	function loadFile(url, callback) {
		PizZipUtils.getBinaryContent(url, callback);
	}
	export default {
		methods: {
			renderDoc() {
				// demo.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
				loadFile("demo.docx", function(
					error,
					content
				) {
					// 抛出异常
					if (error) {
						throw error;
					}
					console.log(content)

					// 创建一个JSZip实例，内容为模板的内容
					var zip = new PizZip(content);
					// 创建并加载docxtemplater实例对象
					var doc = new Docxtemplater().loadZip(zip);
					// 设置模板变量的值
					doc.setData({
						first_name: "John",
						last_name: "Doe",
						phone: "0652455478",
						description: "New Website"
					});
					try {
						// 用模板变量的值替换所有模板变量
						doc.render();
					} catch (error) {
						// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
						function replaceErrors(key, value) {
							if (value instanceof Error) {
								return Object.getOwnPropertyNames(value).reduce(function(
									error,
									key
								) {
									error[key] = value[key];
									return error;
								}, {});
							}
							return value;
						}
						console.log(JSON.stringify({
							error: error
						}, replaceErrors));

						if (error.properties && error.properties.errors instanceof Array) {
							const errorMessages = error.properties.errors
								.map(function(error) {
									return error.properties.explanation;
								})
								.join("\n");
							console.log("errorMessages", errorMessages);
							// errorMessages is a humanly readable message looking like this : 'The tag beginning with "foobar" is unopened'
						}
						throw error;
					}
					// 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
					var out = doc.getZip().generate({
						type: "blob",
						mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
					});
					// 将目标文件对象保存为目标类型的文件，并命名
					saveAs(out, "output.docx");
				});
			}
		},
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
